package cn.zcx;

import java.util.concurrent.TimeUnit;

/**
 * description:interrupt()打断
 * author:zcx
 * lenovo
 * 时间：2022.02.07.19.59
 */
public class Ex4 {
    //方法三
    public static void work() {
        Thread tt = Thread.currentThread();
        String tn = tt.getName();
        System.out.printf("%s启动了%n", tn);
        System.out.printf("%s.isInterrupted() %s%n", tn, tt.isInterrupted());
        while (!tt.isInterrupted()) {
            System.out.printf("%s.isInterrupted() %s%n", tn, tt.isInterrupted());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                break;
            }

        }
        System.out.printf("%s.isInterrupted() %s%n", tn, tt.isInterrupted());
        System.out.printf("%s结束了...%n", tn);
    }

    public static void main(String[] args) {
        //开启线程
        var t = new Thread(Ex4::work, "T1");
        t.start();

        try {
            TimeUnit.SECONDS.sleep(5);
            t.interrupt();
            System.out.println("线程是否被中断：" + t.isInterrupted());//true
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
